<?php

use Core\CashierController;
use Models\Item;
use Models\Spec;
use Models\Category;
use Models\Product;

class GoodsController extends CashierController
{
	/**
	 * 获取基本数据
	 */
	public function basic(){
		$data['pay_types'] = CONFIG('basic.pay_types');
		$units = (new Spec)->order_by('sort','desc')->get();
		$data['units'] = arr_key($units);
		$data['categories'] = (new Category)->where('parent_id',0)->order_by('sort','desc')->get();
		$this->success($data);
	}

	/**
	 * 获取商品信息
	 * @return [JSON] [description]
	 */
	public function index()
	{
		$item = new Item();

		if ($this->input->get('keyword')) {
			//扫描商品一维码获取商品
			$code_items = $item->where('barcode',$this->input->get('keyword'))->get();
			if($code_items){
				foreach ($code_items as $c) {
					$product = new Product();
					$product = $product->find($c['product_id']);
					if(!$product) continue;
					$data = $c;
					$data['p_title'] = $product['title'];
					$data['p_en_title'] = $product['en_title'];
					$data['thumbnail'] = $product['thumbnail'];
					$data['unit'] = $product['unit'];
					return $this->success(['item'=>$data]);
				}

			}
			$item->like('products.title', $this->input->get('keyword'));
		}

		$cate_id = $this->input->get('cate_id');
		if($cate_id){
			if($cate_id == 'hot'){
				//热门商品
				$item->where('products.is_cashier_hot',1);
			}else if($cate_id == 'weight'){
				//称重商品
				$item->where('products.is_weight',1);
			}else{
				//按类别
				$item->where('products.category_id',$cate_id);
			}
		}

		$page = $item
			->select('items.*,products.title as p_title,products.en_title as p_en_title, products.thumbnail,products.unit')
			->join('products', 'products.id=items.product_id')
			->order_by('sort desc')
			->default_filter(false)
			->where('items.is_delete=0 and products.is_delete=0')
			->paginate(12)
			->to_array();

		return $this->success($page);
	}
}
